//
//  Config.m
//  Shuaiche
//
//  Created by zzs on 2017/10/25.
//  Copyright © 2017年 zzs. All rights reserved.
//

#import "Config.h"
#import "AppDelegate.h"
#import "SCHttpManager.h"
#import <JPUSHService.h>
#import <Photos/Photos.h>
#import "NSString+Helper.h"

@interface Config()

@property (nonatomic, weak) UIViewController *presentedViewControoler;


@end

@implementation Config

SINGLETON_FOR_CLASS_IMPLEMENTATION(Config)

- (User *)user{
    if(!_user){
        if([[NSUserDefaults standardUserDefaults] objectForKey:kUserId]){
            NSPredicate *predict = [NSPredicate predicateWithFormat:@"userId == %@",[[NSUserDefaults standardUserDefaults] objectForKey:kUserId]];
            User *user = [User MR_findFirstWithPredicate:predict];
            _user = user;
        }else{
            _user = nil;
            _scUserUnionIds = nil;
        }
    }
    return _user;
}

+ (void)userLogout {
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kUserId];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kMerchantId];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kSessionId];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsLogin];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsRegister];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kMaintenEnable];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"已经解除绑定:%@",iAlias);
    } seq:12];
    
    [Config sharedConfig].user = nil;
    [[SCHttpManager shareInstance] updateHeaderFieldSession:nil];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSCAlertAddAddressKey];
    [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_LOGIN_IN_OUT object:nil];
}

+ (void)showLoginWhenSessionExpired{
  if([Config sharedConfig].isPresentedWhenSessionExpired)return;
  [self logoutWhenSessionExpired];
  [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_LOGIN_IN_OUT object:nil];
}

+ (void)logoutWhenSessionExpired{
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kUserId];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kSessionId];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsLogin];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[SCHttpManager shareInstance] updateHeaderFieldSession:nil];
    [Config sharedConfig].user = nil;
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        
    } seq:10];
}

+ (void)fetchMaintenEnable {
  if ([[NSUserDefaults standardUserDefaults] boolForKey:kMaintenEnable]) {
    return;
  }
  NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
  [param setValue:[Config sharedConfig].user.phone forKey:kPhone];
  [[SCHttpManager shareInstance] httpPost:@"/baseprod/config/bapp" param:param completion:^(id response, NSError *error){
    if (response) {
        NSNumber *carMaintenanceEnable = response[@"carMaintenanceEnable"];
        [[NSUserDefaults standardUserDefaults] setBool:carMaintenanceEnable.boolValue forKey:kMaintenEnable];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_MAINTEN_ENABLE object:nil userInfo:nil];

    } else {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kMaintenEnable];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
  }];
}

- (NSString *)merchantNameOfUser {
    return self.user.merchantAbbreviation.length ? self.user.merchantAbbreviation: self.user.merchantName;
}

- (NSString *)addressOfUser {
    NSMutableString *address = [[NSMutableString alloc] init];
    if(![NSString SC_isBlankString:self.user.provinceName]){
        [address appendString:self.user.provinceName];
    }
    if(![NSString SC_isBlankString:self.user.cityName]){
        [address appendString:self.user.cityName];
    }
    if(![NSString SC_isBlankString:self.user.districtName]){
        [address appendString:self.user.districtName];
    }
    if(![NSString SC_isBlankString:self.user.address]){
        [address appendString:self.user.address];
    }
    if(address.length){
        return address;
    }else{
        return nil;
    }
}

+ (void)savePhotoToCustomAlbumWithName:(NSString *)albumName photo:(UIImage *)photo {
    if (!photo) {
        return;
    }
    // 判断授权状态
    NSError *error = nil;
    // 保存相片到相机胶卷
    __block PHObjectPlaceholder *createdAsset = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdAsset = [PHAssetCreationRequest creationRequestForAssetFromImage:photo].placeholderForCreatedAsset;
    } error:&error];
    if (error) {
    }else{
    }
}

@end
